import pymysql


class DBToolos(object):
    @staticmethod
    def create_conn():
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                               password="iHRM_student_2022", database="ihrm", charset="utf8")
        return conn

    @staticmethod  # 静态方法 装饰器
    def query_one(sql):
        conn = None
        cursor = None
        res = None
        try:
            conn = DBToolos.create_conn()  # 使用类名调用静态方法 创建链接
            cursor = conn.cursor()  # 创建游标
            cursor.execute(sql)  # 执行用户传入的  sql 语句
            res = cursor.fetchone()  # #  提取一条数据

        except Exception as err:
            print("代码运行出现的异常：", err)

        finally:
            cursor.close()  # 关闭游标
            conn.close()  # 关闭连接
            return res  # 返回查询结果  给调用者

    def query_all(self, sql):
        pass

    def query_many(self, size, sql):
        pass

    @staticmethod
    def db_iud(sql):
        conn = None
        cursor = None
        try:
            conn = DBToolos.create_conn()  # 使用类名调用静态方法 创建链接
            cursor = conn.cursor()  # 创建游标
            cursor.execute(sql)  # 执行用户传入的  sql 语句
            conn.commit()
            print("增删改 sql 执行成功")

        except Exception as err:
            print("增删改时，出现异常", err)

        finally:
            cursor.close()  # 关闭游标
            conn.close()  # 关闭连接


if __name__ == '__main__':
    res = DBToolos.query_one("select * from t_book where id = 30")
    print(res)

    DBToolos.db_iud("delete from t_book where id = 30;")
